<template>
	<view class="login">
		<u-toast ref="uToast"></u-toast>
		<view class="face">
			<img src="../../static/logo@1x.jpg" alt="">
		</view>
		<view class="form">
			<u-form labelPosition="left" :model="form" labelWidth="120rpx" :rules="rules" ref="uForm">
				<u-form-item prop="uPhone" ref="item1">
					<u-input placeholder="请输入手机号" maxlength="11" border="surround" shape="circle"
						v-model="form.uPhone"></u-input>
				</u-form-item>
				<u-form-item prop="checkCode" ref="item1">
					<u-input placeholder="请输入验证码" v-model="form.checkCode" maxlength="6" border="surround"
						shape="circle">
						<template slot="suffix">
							<u-code :seconds="seconds" ref="uCode" changeText="X秒重新获取" @change="codeChange"></u-code>
							<u-button @tap="getCode" :text="tips" type="success" shape="circle"
								size="mini">{{tips}}</u-button>
						</template>
					</u-input>
				</u-form-item>
			</u-form>
		</view>
		<view class="btn">
			<u-button type="primary" @click="login">登录</u-button>
			<button class="wx-login" open-type="getUserInfo" @getuserinfo="handleWechatLogin"
				@click="clickWeChartLoading">
				<img src="../../static/wechart.jpg" alt="" />
			</button>
		</view>
		<!-- <view class="agreement">
			<u-checkbox-group v-model="form.consent" placement="column" @change="checkboxChange">
				<u-checkbox name="1"></u-checkbox>
			</u-checkbox-group>
			<view>我已阅读并同意《服务条款》和《隐私政策》</view>
		</view> -->
	</view>
</template>

<script>
	import {
		validateChineseMobile
	} from '@/utils/index.js'
	import API from '@/api';
	export default {
		data() {
			return {
				tips: '',
				seconds: 10,
				avatarUrl: '',
				src: '../../static/1.jpg',
				form: {},
				user: {},
				rules: [],
				loading: false
			}
		},
		beforeCreate() {
			this.user = uni.getStorageSync('userInfo')
			if (this.user) {
				uni.redirectTo({
					url: '/pages/discover/index',
				})
			}
		},
		created() {
			this.$store.commit("common/SET_TABBAR_OBJ", {
				index: 0
			});
		},
		methods: {
			clickWeChartLoading() {
				this.$refs.uToast.show({
					type: 'loading',
					message: '登录中...'
				});
			},
			codeChange(text) {
				this.tips = text;
			},
			async getCode() {
				if (this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					uni.showLoading({
						title: '正在获取验证码'
					})
					const code = await API.sms.sendSms(this.form)
					console.log(code)
					uni.hideLoading();
					uni.$u.toast('验证码已发送');
					this.$refs.uCode.start();
				} else {
					uni.$u.toast('倒计时结束后再发送');
				}
			},
			change(e) {
				console.log('change', e);
			},
			async handleWechatLogin(e) {
				if (e.detail.errMsg === 'getUserInfo:ok') {

					// 1. 获取微信用户信息 
					const userInfo = e.detail.userInfo;

					// 2. 获取code（需先调用uni.login ）
					const loginRes = await uni.login({
						provider: 'weixin'
					});

					if (loginRes.errMsg != 'login:ok') return

					// 3. 发送code到后端换取openid和session_key 
					const res = await uni.request({
						url: 'https://api.tiancihunyue.com/admin/user/wx-login',
						method: 'POST',
						data: {
							code: loginRes.code,
							userInfo: userInfo
						}
					});
					if (res.data.code == 200) {
						this.$store.commit("user/SET_USER_INFO", res.data.data);
						if (res.data.data.isRegister) {
							this.$refs.uToast.show({
								message: '登录成功，请完善您的个人资料',
								complete() {
									this.loading = false
									uni.setStorageSync('token', 'ok');
									uni.redirectTo({
										url: '/pages/my/edit-profile',
									})
								},
							});
						} else {
							this.$refs.uToast.show({
								message: '登录成功',
								complete() {
									this.loading = false
									uni.setStorageSync('token', 'ok');
									uni.redirectTo({
										url: '/pages/discover/index',
									})
								},
							});
						}
					}
				}
			},
			login() {
				if (!this.form.uPhone) {
					this.$refs.uToast.show({
						message: '手机号不能为空'
					});
					return
				}
				if (!validateChineseMobile(this.form.uPhone)) {
					this.$refs.uToast.show({
						message: '请输入正确的手机号码'
					});
					return
				}
				if (!this.form.checkCode) {
					this.$refs.uToast.show({
						message: '验证码不能为空'
					});
					return
				}
				let params = {
					uPhone: this.form.uPhone,
					checkCode: this.form.checkCode
				}
				let loginRes = API.user.login(params)
				if (loginRes) {

					this.$store.commit("user", loginRes);
					this.$refs.uToast.show({
						message: '登录成功',
						complete() {
							this.loading = false
							uni.setStorageSync('token', 'ok');
							uni.redirectTo({
								url: '/pages/discover/index',
							})
						},
					});
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.login {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		gap: 100rpx;
		padding: 10%;

		.face {
			width: 100%;
			height: 300rpx;
			text-align: center;

			img {
				width: 200rpx;
				height: 230rpx;
			}
		}

		.form {
			width: 100%;

			input {
				padding-left: 20rpx;
				width: 100%;
			}
		}

		.btn {
			width: 100%;
			display: flex;
			flex-direction: column;
			gap: 10rpx;
		}

		.agreement {
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: .8em;
		}

		.wx-login-img {
			text-align: center;

			img {
				width: 100rpx;
				height: 100rpx;
				border-radius: 10rpx;
			}
		}

		.wx-login {
			width: 80rpx;
			height: 80rpx;
			text-align: center;
			overflow: hidden;
			padding: 0;

			img {
				width: 100%;
				height: 100%;
			}
		}
	}
</style>